package com.chujian.framework.db.crypto;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.chujian.framework.crypto.ICrypto;

/**
 * @author ：yj
 * @date ：2020-09-16
 */
@Slf4j
public class DefaultDataCrypto implements ICrypto {
    private final AES aes;

    public DefaultDataCrypto() {
        String key = "+ds2mmOTvCJ7/ZWoyMNQmA==";
        aes = SecureUtil.aes(Base64.decode(key));
    }

    public DefaultDataCrypto(String key) {
        aes = SecureUtil.aes(Base64.decode(key));
    }

    @Override
    public String enCrypto(Object object) {
        if (object == null) return null;
        if (object instanceof String) {
            return aes.encryptHex((String) object);
        }
        throw new UnsupportedOperationException("db encrypt must be string type");
    }

    @Override
    public String deCrypto(String str) {
        if (StringUtils.isEmpty(str)) return null;
        try {
            return aes.decryptStr(str);
        } catch (Exception e) {
            log.warn("decode失败：" + str);
            return str;
        }
    }
}
